package com.ahdms.es;

import com.ahdms.es.bean.CertInfo;
import com.ahdms.es.bean.SealInfo;
import com.ahdms.es.bean.SesSignInfo;
import com.ahdms.es.config.PropertiesConfig;
import com.ahdms.es.exceptions.ApiException;
import com.ahdms.es.result.VerifyResult;
import com.ahdms.es.util.Base64Utils;
import com.ahdms.es.util.base64.Base64;
import org.bouncycastle.asn1.x509.Certificate;

import java.util.List;

/**
 * @author qinxiang
 * @date 2021-04-12 11:03
 */
public abstract class EsVerifyEngineDeal {

    public static EsVerifyEngineDeal getInstance(){
        if(!PropertiesConfig.isHasInit()){
            throw new ApiException("配置文件未初始化");
        }
        return new DefaultEsSignEngineDeal();
    }

    /**
     * 文件签章验证
     * @param fileBytes 文件数据
     * @param fileType 文件类型(PDF、OFD)
     * @return
     */
    public abstract List<VerifyResult<SesSignInfo>> verifySignByFile(byte[] fileBytes, String fileType);

    /**
     * 电子签章数据结构验证
     * @param base64Signature 电子签章数据Base64编码
     * @param base64Src 原文的Base64编码
     * @return
     */
    public VerifyResult<SesSignInfo> verifySignBySignatureData(String base64Signature,String base64Src){
        return verifySignBySignatureData(Base64Utils.decode(base64Signature),Base64Utils.decode(base64Src));
    }

    /**
     * 电子签章数据结构验证
     * @param signature 电子签章数据
     * @param src 原文数据
     * @return
     */
    public abstract VerifyResult<SesSignInfo> verifySignBySignatureData(byte[] signature, byte[] src);

    /**
     * X509格式证书 验证
     * @param base64CertData X509格式证书Base64编码
     * @return
     */
    public VerifyResult<CertInfo> verifyX509Cert(String base64CertData) {
        Certificate cert;
        try {
            cert = Certificate.getInstance(Base64Utils.decode(base64CertData));
        } catch (Exception e) {
            return VerifyResult.error("证书数据有误,解析失败!");
        }
        return verifyX509Cert(cert);

    }

    /**
     * X509格式证书 验证
     * @param cert X509格式证书数据
     * @return
     */
    public abstract VerifyResult<CertInfo> verifyX509Cert(Certificate cert);

    public VerifyResult<CertInfo> verifyX509Cert(byte[] certBytes){
        Certificate cert;
        try {
            cert = Certificate.getInstance(certBytes);
        }catch (Exception e){
            return VerifyResult.error("证书数据有误,解析失败!");
        }
        return verifyX509Cert(cert);
    }

    /**
     * 电子印章验证
     * @param base64SealData 电子印章数据Base64编码
     * @return
     */
    public VerifyResult<SealInfo> verifySeal(String base64SealData) {
        return verifySeal(Base64Utils.decode(base64SealData));
    }

    /**
     * 电子印章验证
     * @param sealData 电子印章数据
     * @return
     */
    public abstract VerifyResult<SealInfo> verifySeal(byte[] sealData);

}
